package com.qf.utils;

import com.qf.consants.RabbitMQConstants;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class OrderUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //    时间+用户Id后四位+四位随机数+商家的编号+流水号
    public String createOrderId(Integer uid) {

        StringBuffer buffer = new StringBuffer();

        // 当前时间
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());

        // 用户id后四位
        String sufUserId = getUserSufId(uid.toString());

        // 四位随机数
        String random = RandomStringUtils.random(4, false, true);

        // 商家 --》根据商品查询商家的Id

        // 流水号
        String redisIndex = getRedisIndex();

        // 拼接
        buffer.append(date).append(sufUserId).append(random).append(redisIndex);
        return buffer.toString();
    }

    public String getUserSufId(String uid) {

        StringBuffer buffer = new StringBuffer();

        // 1.先判断用户id是否满足四位，不满足就用填充
        if (uid.length() < 4) {
            for (int i = 0; i < (4 - uid.length()); i++) {
                buffer.append("0"); // 补零
            }
            buffer.append(uid); // 加上UID
        } else {
            buffer.append(uid.substring(uid.length() - 4));
        }
        return buffer.toString();
    }

    public static void main(String[] args) {


        OrderUtils orderUtils = new OrderUtils();

        String userSufId = orderUtils.getUserSufId("12");
        System.out.println(userSufId);

        System.out.println(orderUtils.getUserSufId("1234567890"));

        String random = RandomStringUtils.random(4, false, true);
        System.out.println(random);
    }

    public String getRedisIndex() {
        Long index = stringRedisTemplate.opsForValue().increment(RabbitMQConstants.REDIS_ORDER_INDEX);
        return index.toString();
    }

    public Integer getUserSufIdByOrderId(String oid) {
        //
        return Integer.parseInt(oid.substring(8,8+4));
    }
}
